package com.borened.netty.protocol.http;

import com.borened.netty.util.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author chengcaihua
 * @description 请求分发一级处理器
 * @since 2023-11-14 14:25
 */
@Slf4j
@ChannelHandler.Sharable
@Component
public class HttpRequestDispatchHandler  extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        FullHttpRequest request = (FullHttpRequest) msg;

        // 处理HTTP请求
        String uri = request.uri();
        String requestBody = ByteBufUtil.readString(request.content());
        HttpMethod method = request.method();
        log.info("handle http request uri: {}, method:{}, body:{} ", uri, method, requestBody);
        // todo 根据uri，匹配目标类和目标方法。可以模仿SpringMvc的DispatcherServlet
        String name = uri.substring(uri.lastIndexOf("/"));
        // 构建HTTP响应
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK,
                Unpooled.copiedBuffer("Hello, "+name+"!", CharsetUtil.UTF_8));
        // 设置响应头
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN);
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
        response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        // 发送响应
        ctx.writeAndFlush(response);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("http request handle error ", cause);
        ctx.close();
        super.exceptionCaught(ctx, cause);
    }

}
